package com.rainbow.support.xss.warpper;

import com.rainbow.common.core.error.GlobalException;
import com.rainbow.common.core.toolkit.SpringBeanUtil;
import com.rainbow.support.xss.handler.JsonXssCleaner;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * XSS过滤处理
 * @author rainbow
 */
@Slf4j
public class XssRequestWrapper extends HttpServletRequestWrapper {
	/**
	 * 没被包装过的HttpServletRequest（特殊场景，需要自己过滤）
	 */
	HttpServletRequest orgRequest;


	public XssRequestWrapper(HttpServletRequest request) {
		super(request);
		orgRequest = request;
	}

	@Override
	public String getParameter(String name) {
		String value = super.getParameter(clean(name));
		if (StringUtils.isNotBlank(value)) {
			value = clean(value);
		}
		return value;
	}

	@Override
	public String[] getParameterValues(String name) {
		String[] parameters = super.getParameterValues(name);
		if (parameters == null || parameters.length == 0) {
			return null;
		}
		for (int i = 0; i < parameters.length; i++) {
			parameters[i] = clean(parameters[i]);
		}
		return parameters;
	}

	@Override
	public Map<String, String[]> getParameterMap() {
		Map<String, String[]> map = new LinkedHashMap<>();
		Map<String, String[]> parameters = super.getParameterMap();
		for (String key : parameters.keySet()) {
			String[] values = parameters.get(key);
			for (int i = 0; i < values.length; i++) {
				values[i] = clean(values[i]);
			}
			map.put(key, values);
		}
		return Collections.unmodifiableMap(map);
	}


	@Override
	public String getHeader(String name) {
		String value = super.getHeader(clean(name));
		if (StringUtils.isNotBlank(value)) {
			value = clean(value);
		}
		return value;
	}

	@Override
	public String getQueryString() {
		String value = super.getQueryString();
		if (value == null) {
			return null;
		}
		return clean(value);
	}

	@Override
	public Object getAttribute(String name) {
		Object value = super.getAttribute(name);
		if (value instanceof String) {
			clean(Objects.toString(value));
		}
		return value;
	}

	/**
	 * xss过滤
	 * @param input 待处理参数
	 * @return 过滤结果
	 */
	private String clean(String input) {
		return Objects.requireNonNull(SpringBeanUtil.getBean("xssCleaner", JsonXssCleaner.class)).escape(input);
	}

	/**
	 * SQL注入过滤检查
	 * @param str  待验证的字符串
	 */
	public static String sqlInject(String str){
		//sql关键字
		String[] keywords = {"master","and","exec","count","*","%","or","truncate", "insert", "select", "delete", "update", "declare", "alert", "drop"};
		if(StringUtils.isBlank(str)){
			return null;
		}
		String originParam=str;
		//去掉'|"|;|\字符
		str = StringUtils.replace(str, "'", "");
		str = StringUtils.replace(str, "\"", "");
		str = StringUtils.replace(str, ";", "");
		str = StringUtils.replace(str, "\\", "");
		//判断是否包含非法字符
		for(String keyword : keywords) {
			if (StringUtils.containsIgnoreCase(str, keyword)) {
				log.warn("参数:{}含有非法字符,已禁止继续访问!",originParam);
				throw new GlobalException("参数含有非法字符,已禁止继续访问!");
			}
		}
		return str;
	}

	/*此处注释,参数json在json反序列化时,已经处理
	@Override
	public ServletInputStream getInputStream() throws IOException {
		// 非json类型，直接返回
		if (!MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(super.getHeader(HttpHeaders.CONTENT_TYPE))) {
			return super.getInputStream();
		}
		// 为空，直接返回
		String json = IOUtils.toString(super.getInputStream(), Charset.forName("utf-8"));
		if (StringUtils.isBlank(json)) {
			return super.getInputStream();
		}
		// xss过滤
		json = clean(json);
		final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes("utf-8"));
		return new ServletInputStream() {
			@Override
			public boolean isFinished() {
				return true;
			}

			@Override
			public boolean isReady() {
				return true;
			}
			@Override
			public void setReadListener(ReadListener readListener) {

			}
			@Override
			public int read() throws IOException {
				return bis.read();
			}
		};
	}*/
}
